package com.mxx.common.conv;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.mxx.common.utils.Strings;

import java.io.IOException;

/**
 * 扩展 Boolean 支持数字，非零即为 true
 */
public class BooleanDeserializer extends JsonDeserializer<Boolean> {

    @Override
    public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        if (p.getCurrentToken().isNumeric()) {
            int intValue = p.getIntValue();
            return intValue != 0;
        } else {
            String text = p.getText().trim();
            try { // 尝试强转 应对数值类型的字符串
                if (Strings.isEmpty(text)) {
                    return false;
                }
                return Long.parseLong(text) != 0;
            } catch (Exception ignored) {
            }
            JsonToken t = p.currentToken();
            if (t == JsonToken.VALUE_TRUE) {
                return true;
            } else if (t == JsonToken.VALUE_FALSE) {
                return false;
            } else if (text.equalsIgnoreCase("true")) {
                return true;
            } else if (text.equalsIgnoreCase("false")) {
                return false;
            } else {
                throw (new JsonParseException(p, String.format("Current token (%s) not of boolean type", t))).withParser(p);
            }

        }
    }
}
